# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         ext_redis.py
# Description:
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2021/8/16 20:30
# -------------------------------------------------------------------------------
import json

from apps.SystemService.models import Parameter
from utils.redis_client import RedisClient

__all__ = ['RedisDB']


class RedisDB(object):
    def __init__(self, redis_tag, db=None):
        """
        初始化
        Args:
            redis_tag:redis数据库标识
            db:数据库
        """
        self.redis_tag = redis_tag
        self.db = db
        self.redis_conf = {}
        parameter = Parameter.objects.filter(key='REDIS_CONFIG', is_deleted=False).first()
        if parameter and parameter.value:
            data = json.loads(parameter.value)
            self.redis_conf = self.parse_db_conf(data=data)
        self.redis_client = RedisClient(**self.redis_conf)

    def parse_db_conf(self, data):
        """
        解析数据库配置信息
        Args:
            data:

        Returns:

        """
        if isinstance(data, dict):
            if self.redis_tag and self.redis_tag == data.get('redis_tag'):
                return {
                    'host': data.get('host', '127.0.0.1'),
                    'port': data.get('port', 6379),
                    'password': data.get('password', None),
                    'db': data.get('db', 0) if self.db is None else self.db,
                    'ssh_host': data.get('ssh_host', None),
                    'ssh_username': data.get('ssh_username', None),
                    'ssh_password': data.get('ssh_password', None),
                    'use_ssh_tunnel': data.get('use_ssh_tunnel', False)
                }
        elif isinstance(data, list):
            res = None
            for item in data:
                res = self.parse_db_conf(item)
                if res is not None:
                    break
            return res

    def get(self, name):
        """

        Args:
            name:redis的key

        Returns:

        """
        return self.redis_client.get(name)
